//
//  ObjectMapper+Unwarp.swift
//  YD_DataModel
//
//  Created by 钟志远 on 2021/11/29.
//  Copyright © 2021 alyadan. All rights reserved.
//

import Foundation
import ObjectMapper
import Moya
import RxSwift
import SwiftyJSON

public extension Mappable {
    static func fetchModel<T: TargetType>(target: T, dataKeyPath: String? = nil, makeProvider: ((T) -> MoyaProvider<T>)? = nil) -> Observable<(Self?, JSON)> {
        return YDNetworkTool.requestRx(target: target, makeProvider: makeProvider)
            .map { (data: JSON) -> (Self?, JSON) in
                (self.init(JSON: data.json(keyPath: dataKeyPath).dictionaryObject ?? [:]), data)
            }.share(replay: 1)
    }
    
    static func genModel(data: JSON, dataKeyPath: String? = "data") -> (Self?, JSON){
        (self.init(JSON: data.json(keyPath: dataKeyPath).dictionaryObject ?? [:]), data)
    }
}


public extension Array where Element: Mappable {
    
    static func fetchModel<T: TargetType>(target: T, dataKeyPath: String? = nil, makeProvider: ((T) -> MoyaProvider<T>)? = nil) -> Observable<([Element]?, JSON)> {
        return YDNetworkTool.requestRx(target: target, makeProvider: makeProvider)
            .map { (data: JSON) -> ([Element]?, JSON) in
                return ([Element].init(JSONString: data.json(keyPath: dataKeyPath).rawString() ?? ""), data)
            }.share(replay: 1)
    }
    
    static func genModel(data: JSON, dataKeyPath: String? = "data") -> (Self?, JSON){
        return ([Element].init(JSONString: data.json(keyPath: dataKeyPath).rawString() ?? ""), data)
    }
}

public extension JSON {
     func json(keyPath: String?) -> JSON {
        guard let keyPath = keyPath else {
            return self
        }
        
        
        let keys = keyPath.components(separatedBy: ".")
        var result = self
        for key in keys {
            if key == "" {
                continue
            }
            result = result[key]
        }
        
        return result
    }
}
